# Notify class - Displays Entertainer notifications using Libnotify
# Copyright (C) 2007 Lauri Taimila
# 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

__licence__ = "GPLv2"
__copyright__ = "2007, Lauri Taimila"
__author__ = "Lauri Taimila <lauri@taimila.com>"

import os
import logging
import pynotify

from utils.configuration import Configuration
from backend.core.message_type_priority import MessageType, MessagePriority
from backend.core.message_handler import MessageHandler

#from utils.resolve_dialog import ConflictResolveDialog

class Notify(MessageHandler):
    """
    Notify class provides easy way to display notification bubbles
    
    This class uses libnotify library to display notification bubbles.
    Application can call notifyXXX() -methods to display notifications.
    Notifications can be extended easily by adding new methods to this
    class. Notify.connectNotificationServer() must be called before any
    notifications can be displayed.
    """

    def __init__(self, logger, configuration):
        """Notify constructor.
        
           param logger - Logger object that is notified when errors occur.
        """
        self.connected = False # Is Notify connected to the Notification server
        self.enabled = True # Is notification bubbles enabled (if it is we show notifications)
        self.logger = logger
        self.configuration = configuration
            
    def connectNotificationServer(self):
        """Registers this application to notification server."""
        if pynotify.init("Entertainer"):
            self.connected = True
        else:
            raise Exception("Couldn't connect to notification server")
    
    def disconnectNotificationServer(self):
        """Unregisters this application from notification server."""
        self.connected = False
        pynotify.uninit()
    
    def openConflictResolvingDialog(self, notification=None, action=None, data=None):
        #crd = ConflictResolveDialog()
        pass
        
    def notifyRecordingBegins(self,channel, show):
        """Displays notification that recording has been started."""
        if self.connected and self.configuration.isNotificationsEnabled():
            msg_body = "Recording <b>" + show + "</b> from the channel <b>" + channel + "</b>."
            n = pynotify.Notification("Recording TV", msg_body, "gtk-media-record")
            n.set_urgency(pynotify.URGENCY_NORMAL)
            n.set_timeout(8000) # 8 seconds
            n.show()
        else:
            self.logger.warning("Couldn't display notification")
        
    
    def notifyRecordingEnds(self, channel, show):
        """Displays notification that recording has been finished."""
        if self.connected and self.configuration.isNotificationsEnabled():
            msg_body = "Recording <b>" + show + "</b>  from the channel <b>" + channel + "</b>  was finished."
            n = pynotify.Notification("Recording finished", msg_body, "gtk-ok")
            n.set_urgency(pynotify.URGENCY_NORMAL)
            n.set_timeout(8000) # 8 seconds
            n.show()
        else:
            self.logger.warning("Couldn't display notification")
         
    def notifyRecordingConflict(self):
        """Displays notification that there is a conflict between recordings."""
        if self.connected and self.configuration.isNotificationsEnabled():
            msg_body = "There is a conflict between two or more recordings. Entertainer needs you to resolve this conflict."
            n = pynotify.Notification("Recording conflict", msg_body, "dialog-warning")
            n.set_urgency(pynotify.URGENCY_NORMAL)
            n.set_timeout(pynotify.EXPIRES_NEVER)
            n.add_action("clicked","Resolve conflict", self.openConflictResolvingDialog, None)
            n.show()
        else:
            self.logger.warning("Couldn't display notification")
    
    def notifyError(self, message, autoclose):
        """Displays error notification."""
        if self.connected and self.configuration.isNotificationsEnabled():
            n = pynotify.Notification("Entertainer Error",message, "dialog-error")
            n.set_urgency(pynotify.URGENCY_CRITICAL)
            if autoclose:
                n.set_timeout(8000) # 8 seconds
            else:
                n.set_timeout(pynotify.EXPIRES_NEVER)
            n.show()
        else:
            self.logger.warning("Couldn't display notification")
    
    # Implements MessageHandler interface
    def handleMessage(self, message):
        """Handle received messages. (Implements MessageHandler interface)"""
        if message.get_type() == MessageType.RECORDING_CONFLICT:
            self.notifyRecordingConflict()
        elif message.get_type() == MessageType.RECORDING_STARTED:
            #FIXME: Read real values from Message data
            self.notifyRecordingBegins("","")
        elif message.get_type() == MessageType.RECORDING_STOPPED:
            #FIXME: Read real values from Message data
            self.notifyRecordingEnds("","")
                    
    def getName(self):
        return "Notification System"
